const md5 = require("md5");
const {loginDao, updateAdminDao} = require("../dao/adminDao");
const jwt = require('jsonwebtoken');
const {ValidationError} = require("../utils/errors");
const {formatResponse} = require("../utils/tool");

// 登录
module.exports.loginService = async function (loginInfo) {
    loginInfo.loginPwd = md5(loginInfo.loginPwd);
    const result = await loginDao(loginInfo);
    if (result && result.dataValues) {
        // 获取数据表字段对象
        const data = {
            id: result.dataValues.id,
            loginId: result.dataValues.loginId,
            name: result.dataValues.name
        }
        // 免登录持续时长
        let loginPeriod = null
        if(loginInfo.remember) {
            loginPeriod = parseInt(loginInfo.remember)
        } else {
            loginPeriod = 1
        }
        // 生成 token
        const token = jwt.sign({
            id: data.id,
            loginId: data.loginId,
            name: data.name
        }, md5(process.env.JWT_SECRET),{
            expiresIn: loginPeriod * 60 * 60 * 24
        })
        return {
            data,
            token
        }
    }
    return {result};
}

// 更新用户信息
module.exports.updateAdminService = async function (accountInfo) {
    const adminInfo = await loginDao({
        loginId: accountInfo.loginId,
        loginPwd: md5(accountInfo.oldLoginPwd)
    })
    if (adminInfo && adminInfo.dataValues) {
        const newPassword = md5(accountInfo.loginPwd)
        // 返回更新的字段数 比如 [1] 就是更新了1条数据
        const result = await updateAdminDao({
            name: accountInfo.name,
            loginId: accountInfo.loginId,
            loginPwd: newPassword
        })
        return formatResponse(0, '', {
            loginId: accountInfo.loginId,
            name: accountInfo.name,
            id: adminInfo.dataValues.id
        })
    } else {
        throw new ValidationError("旧密码错误")
    }
}